package org.hismig.test.migration;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import junit.framework.TestCase;

import org.hismig.cfg.Configuration;
import org.hismig.cfg.Param;
import org.hismig.cfg.Trigger;
import org.hismig.migration.Constructor;
import org.hismig.migration.result.JobResultInfo;
import org.hismig.scheduler.ITrigger;
import org.hismig.scheduler.TriggerListenerAdapter;

/**
 * @declare: //TODO <br />
 *           This class created by Vansion.Hopihit on 2012-07-04 <br />
 *           <a href="mailto:vansionhopihit@gmail.com">Contact Me</a>
 * @version 1.0
 * @author Vansion.Hopihit
 * 
 */
public class TriggerTester extends TestCase {

	private Constructor constructor;
	private Configuration configuration;

	@Override
	protected void setUp() throws Exception {
		configuration = new Configuration(TriggerTester.class.getResource(
				"HisMig.cfg.xml").toURI());
		constructor = new Constructor();
		constructor.init(configuration);
	}

	public void testTrigger() {

		ITrigger trigger = constructor.getTrigger();

		Trigger triggerCfg = configuration.getTrigger();
		List<Param> params = triggerCfg.getParams();
		for (Param param : params) {

			if (param.getName().equals("expression")) {

				String hour = new SimpleDateFormat("HH").format(new Date());
				int min = Integer.parseInt(new SimpleDateFormat("mm")
						.format(new Date()));

				param.setValue(String.format("0 %s %s * * ? *", new Object[]{
						min + 1, hour}));
			}

		}

		trigger.addListener(new TriggerListenerAdapter() {
			@Override
			public void afterTriggerEnd(JobResultInfo jobResultInfo) {

				assertEquals(0, jobResultInfo.getErrorCount());
				
				Thread.interrupted();
			}
		});

		trigger.execute(configuration);

		try {
			Thread.sleep(120 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

}
